<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增CDN自动部署任务')" />
    <th:block th:include="include :: datetimepicker-css" />
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <h4 class="form-header h4">添加CDN自动部署任务</h4>
    <form class="form-horizontal m" style="width: 800px;" id="form-autoDeploy-add">
        <input type="hidden" name="isYzOver" id="isYzOver">
        <input type="hidden" id="otherJsonList">
        <input type="hidden" name="otherJson" id="otherJson">
        <input type="hidden" id="dnsCount">
        <input type="hidden" id="rrVal0">
        <input type="hidden" id="rrVal1">
        <div class="row">
            <div class="col-xs-12">
                <div class="form-group" style="display: flex;">
                    <label class="control-label is-required" style="text-align: right; width: 150px;">云厂商：</label>
                    <div class="">
                        <div style="display: flex; cursor: pointer;">
                            <div id="cloudVendor1" class="inputDiv sed" onclick="setSelectVal('cloudVendor', 3, 1, 'aly')">
                                <img th:src="@{/img/aliyun.svg}"  alt="阿里云" style="width: 18px; height: 18px; margin-right: 5px;"/>阿里云
                            </div>
                            <div id="cloudVendor2" class="inputDiv" onclick="setSelectVal('cloudVendor', 3, 2, 'qny')">
                                <img th:src="@{/img/qiniu.svg}"  alt="七牛云" style="width: 18px; height: 18px; margin-right: 5px;"/>七牛云
                            </div>
                            <div id="cloudVendor3" class="inputDiv" onclick="setSelectVal('cloudVendor', 3, 3, 'txy')">
                                <img th:src="@{/img/tencent.svg}"  alt="腾讯云" style="width: 18px; height: 18px; margin-right: 5px;"/>腾讯云
                            </div>
                        </div>
                        <input id="cloudVendor" name="cloudVendor" class="form-control" type="hidden">
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group" style="display: flex;">
                    <label class="control-label is-required" style="text-align: right; width: 150px;" id="keyId">AccessKey ID：</label>
                    <div class="input-group m-b" style="width: 500px;">
                        <input value="" id="accessKeyId" name="accessKeyId" class="form-control" placeholder="请输入AccessKey ID" type="text" required>
                        <span onclick="selectCsKeyList()" class="input-group-addon" style="cursor: pointer; color: #5B89FE;">&nbsp;选择</span>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group" style="display: flex;">
                    <label class="control-label is-required" style="text-align: right; width: 150px;" id="keySecret">AccessKey Secret：</label>
                    <div style="width: 500px;">
                        <input value="" id="accessKeySecret" type="text" name="accessKeySecret" placeholder="请输入AccessKey Secret" class="form-control" required>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group" style="display: flex;">
                    <label class="control-label is-required" style="text-align: right; width: 150px;">云产品：</label>
                    <div style="padding: 5px 0;" id="cloudProductList">
                        <label><input type="radio" checked value="aly-cdn" name="cloudProduct">&nbsp;&nbsp;CDN</label>
                        <label style="margin-left: 10px;"><input type="radio" value="aly-dcdn" name="cloudProduct">&nbsp;&nbsp;DCDN</label>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group" style="display: flex;">
                    <label class="control-label is-required" style="text-align: right; width: 150px;">证书域名：</label>
                    <div class="input-group m-b" style="width: 500px;">
                        <select class="form-control m-b" name="certificateDomain" id="certificateDomain">
                            <option value="">请选择证书域名</option>
                        </select>
                        <span onclick="getDomainList()" class="input-group-addon" style="cursor: pointer; color: #5B89FE;"><i class="fa fa-refresh"></i>&nbsp;&nbsp;刷新</span>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group" style="display: flex;">
                    <label class="control-label is-required" style="text-align: right;width: 150px;">证书类型：</label>
                    <div class="" style="width: 500px;">
                        <div style="display: flex; cursor: pointer;">
                            <div id="isUniversal1" class="inputDiv sed" onclick="setSelectVal('isUniversal', 2, 1, 'N')">
                                单域名证书
                            </div>
                            <div id="isUniversal2" class="inputDiv" onclick="setSelectVal('isUniversal', 2, 2, 'Y')">
                                通配符证书
                            </div>
                        </div>
                        <input id="isUniversal" name="isUniversal" class="form-control" type="hidden">
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group" style="display: flex;">
                    <label class="control-label is-required" style="text-align: right; width: 150px;">绑定域名：</label>
                    <div class="input-group m-b" style="width: 500px;">
                        <input type="hidden" name="domainTxt" class="form-control" id="domainTxt">
                        <input type="text" placeholder="自动查询系统证书域名" disabled class="form-control" id="domainDesc">
                        <span class="help-block m-b-none" style="color: red;"><i class="fa fa-info-circle"></i>如果系统中已存在产品通配证书或匹配的单证书，则直接添加，无需验证DNS！</span>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group" style="display: flex;">
                    <label class="control-label is-required" style="text-align: right; width: 150px;">续签到期时间：</label>
                    <div style="width: 500px;">
                        <input type="text" name="autoExpiredTime" class="form-control" id="datetimepicker-demo-2" placeholder="yyyy-MM-dd" required>
                        <span class="help-block m-b-none" style="color: red;"><i class="fa fa-info-circle"></i>如果到期了，该证书就停止自动续签、部署</span>
                    </div>
                </div>
            </div>
            <div class="col-xs-12" id="domainYz">
                <div class="form-group" style="display: flex;">
                    <label class="control-label is-required" style="text-align: right; width: 150px;">域名验证：</label>
                    <div class="input-group m-b">
                        <div class="table-responsive">
                            <p class="is-required">&nbsp;请配置以下DNS解析记录(配置成功后，<text style="color: red; font-weight: bold;font-size: 18px;">请勿删除记录</text> )不删除解析记录，自动续签就可以免验证。</p>
                            <table class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th style="width: 88px;">状态</th>
                                        <th style="width: 238px;">主机记录</th>
                                        <th style="width: 88px;">记录类型</th>
                                        <th style="width: 388px;">记录值</th>
                                        <th style="width: 88px;">操作</th>
                                    </tr>
                                </thead >
                                <tbody id="tableBody">
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group" style="display: flex;">
                    <label class="control-label" style="text-align: right; width: 150px;">备注描述：</label>
                    <div style="width: 500px;">
                        <textarea name="remark" class="form-control"></textarea>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-paper-plane"></i>立即提交</button>
                <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关闭提交</button>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: datetimepicker-js" />
<script th:inline="javascript">
    var domainData = null;
    var prefix = ctx + "SSL/autoDeployIndex"
    $("#form-apply-add").validate({
        focusCleanup: true
    });

    //监听域名的变动格式是否正确
    document.getElementById("certificateDomain").addEventListener("keyup", function(event) {
        const inputValue = event.target.value.replaceAll("。",".").replace(/\s+/g, "").replaceAll("，",",").replace(/\s+/g, "");
        $("#certificateDomain").val(inputValue);
    });
    //获取到域名列表
    function getDomainList(){
        if(!$("#accessKeyId").val()||!$("#accessKeySecret").val()){
            //请求第三方信息
            if (!$.validate.form()) {
                return;
            }
        }
        var cs = $("#cloudVendor").val();
        var tmpVal = $('input[type="radio"][name="cloudProduct"]:checked').val();
        $.modal.loading("数据请求中，请稍后....");
        $.ajax({
            url: ctx + "SSL/autoDeployIndex/getDomainByCsAndKeySercet?cs="+ cs +"&cloudProduct="+tmpVal+"&accessKeyId="+ $("#accessKeyId").val() +"&accessSecret="+ $("#accessKeySecret").val(),
            type: 'get',
            success:function (res){
                $.modal.closeLoading();
                $("#certificateDomain").html('');
                $("#tableBody").html('');
                if(res.code === 0){
                    $.modal.msgSuccess("域名信息查询成功！");
                    if(res.data.length < 1){
                        $("#certificateDomain").append("<option value=''>未查询到域名</option>");
                    }else{
                        $("#certificateDomain").append("<option value=''>请选择证书域名</option>");
                        $("#otherJsonList").val(JSON.stringify(res.data));
                        for(var i=0; i < res.data.length; i ++){
                            if(cs === 'aly'){
                                $("#certificateDomain").append("<option value='"+res.data[i].domainName+"'>"+res.data[i].domainName+"</option>");
                            }else if(cs === 'qny'){
                                $("#certificateDomain").append("<option value='"+res.data[i].name+"'>"+res.data[i].name+"</option>");
                            }else if(cs === 'txy'){
                                if(res.data[i].domain){
                                    $("#certificateDomain").append("<option value='"+res.data[i].domain+"'>"+res.data[i].domain+"</option>");
                                }else{
                                    $("#certificateDomain").append("<option value='"+res.data[i].domainName	+"'>"+res.data[i].domainName	+"</option>");
                                }
                            }
                        }
                    }
                }else{
                    $.modal.msgError(res.msg);
                }
            },
            field:function (error){
                $.modal.closeLoading();
            }
        })
    }

    function selectCsKeyList() {
        var url = ctx + 'SSL/cloudKeySecret/selectKeyInfo?cloudVendor='+$("#cloudVendor").val();
        $.modal.customOpen("选择云厂商访问秘钥", url, "确定", "取消", null, 500, function(index,data){
            $.modal.close(index);
            $.modal.loading("数据请求中，请稍后....");
            $.ajax({
                url: ctx + "SSL/cloudKeySecret/detail/"+data[0],
                type: 'get',
                success:function (res){
                    $.modal.closeLoading();
                    if(res.code === 0){
                        var keyInfo = res.data;
                        $("#accessKeyId").val(keyInfo.accessKeyId);
                        $("#accessKeySecret").val(keyInfo.accessKeySecret);
                        getDomainList();
                    }else{
                        $.modal.msgError(res.msg);
                    }
                },
                field:function (error){
                    $.modal.closeLoading();
                }
            })
        });
    }
    //设置默认值
    $(function() {
        $("#datetimepicker-demo-2").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });
        $("#cloudVendor").val("aly");
        $("#isUniversal").val("N");
        $("#accessKeyId").change(function(e){
            getDomainList();
        });
        $("#accessKeySecret").change(function(e){
            getDomainList();
        });
        $("input[type='radio'][name='cloudProduct']").change(function (e){
            getDomainList();
        })
        //监听域名input发生变化
        $("#certificateDomain").change(function (e){
            console.log(e.target.selectedIndex);
            var tmpJson = JSON.parse($("#otherJsonList").val())
            if(e.target.selectedIndex > 0){
                $("#otherJson").val('{"cloudDomainInfo":'+JSON.stringify(tmpJson[e.target.selectedIndex-1])+'}');
                getSysDomain();
            }
        })
    })

    function getSysDomain(){
        if($("#certificateDomain").val()) {
            $.ajax({
                url: ctx + "SSL/domain1/deployDomainList",
                data: {
                    "certificateDomain": $("#certificateDomain").val(),
                    "isUniversal": $("#isUniversal").val(),
                    "status": "3"
                },
                type: 'post',
                success: function (res) {
                    $.modal.closeLoading();
                    if (res.code === 0) {
                        console.log(typeof res.data);
                        if(typeof res.data === 'string'){
                            $("#domainTxt").val(res.data);
                            $("#domainDesc").val("系统中未查询到该域名证书【" + res.data + "】,系统将自动创建证书！");
                            $("#domainYz").show();
                            $("#isYzOver").val("N");
                            getYzDomain($("#domainTxt").val());
                        }else{
                            $("#domainTxt").val(res.data.certificateDomain);
                            $("#domainDesc").val(res.data.certificateDomain)
                            $("#domainYz").hide();
                            $("#isYzOver").val("Y");
                        }
                    }
                },
                field: function (error) {
                    $.modal.closeLoading();
                }
            })
        }
    }

    function getYzDomain(domainTxt){
        $.modal.loading("数据校验中，请稍后....");
        $.ajax({
            url: ctx + "SSL/domain1/applyBefore?domainName="+ domainTxt,
            type: 'get',
            success:function (res){
                $("#isYzOver").val('N');
                $("#tableBody").html('');
                $.modal.closeLoading();
                if(res.code === 0){
                    $("#dnsCount").val(res.data.length);
                    for(var i=0; i < res.data.length; i ++){
                        $("#tableBody").append("<tr>" +
                            "<td id='yzStatus"+i+"' style='color: red; font-weight: bold;'><i class='fa fa-close'></i>待配置</td>" +
                            "<td style=\"color: #5B89FE;\">"+res.data[i].rrKeyWord+"<i style='margin-left: 9px;' onclick='copyToClipboard(\"" + res.data[i].rrKeyWord + "\")' class='fa fa fa-clone'></i></td>" +
                            "<td style='color: red; font-weight: bold;'>CNAME</td>" +
                            "<td style=\"color: #5B89FE;\">"+res.data[i].rrVal+"<i style='margin-left: 9px;' onclick='copyToClipboard(\"" + res.data[i].rrVal + "\")' class='fa fa fa-clone'></i></td>" +
                            "<td><a class='btn btn-success btn-xs' href='javascript:void(0)' onclick='verifyDNSExist(\"" + domainTxt + "\",\"" + res.data[i].rrKeyWord + "\", \"" + res.data[i].domainName + "\",\"" + res.data[i].rrVal + "\",\"" + i + "\")'><i class='fa fa-paper-plane'></i>&nbsp;验证</a></td>" +
                            "</tr>");
                    }
                }else{
                    $.modal.msgError(res.msg);
                }
            },
            field:function (error){
                $.modal.closeLoading();
            }
        })
    }

    function verifyDNSExist(domainTxt,rrKeyWord,domainName,rrVal, idx){
        $.modal.loading("验证中，请稍后....");
        $.ajax({
            url: ctx + "SSL/domain1/verifyDNSExist?domainTxt="+domainTxt+"&domainName="+(rrKeyWord+"."+domainName)+"&rrVal="+rrVal,
            type: 'get',
            success: function (res1) {
                $.modal.closeLoading();
                if(res1.code === 0){
                    $("#yzStatus"+idx).html("<i class='fa fa-check'></i>已配置");
                    $("#yzStatus"+idx).css('color', "#12B980");
                    $("#rrVal"+idx).val("Y");
                    //判断验证个数
                    let dnsCount = parseInt($("#dnsCount").val());
                    if(dnsCount < 2){
                        if($("#rrVal0").val()){
                            $("#isYzOver").val('Y');
                            $("#checkResult").css('color', "#12B980");
                        }
                    }else{
                        if($("#rrVal0").val()&&$("#rrVal1").val()){
                            $("#isYzOver").val('Y');
                            $("#checkResult").css('color', "#12B980");
                        }
                    }
                    $.modal.msgSuccess("验证成功！");
                }else{
                    $.modal.msgWarning("未查询到dns解析记录或记录未生效！");
                }
            },
            field: function (error) {}
        })
    }
    //获取到当前时间戳
    function formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    //复制数据fa fa-check
    function copyToClipboard(text) {
        var textarea = document.createElement('textarea');
        textarea.style.position = 'fixed';
        textarea.style.opacity = 0;
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        $.modal.msgSuccess("复制成功！");
    }
    //效果展示
    function setSelectVal(idName, idLen, idx, val){
        $("#"+idName).val(val);
        //证书颁发机构变更验证信息
        if(idName === 'issuingAuthority'){
            if(idx !== 1){
                $.modal.msgWarning("开发中...");
                return;
            }
        }
        //证书类型变更重新获取验证信息
        if(idName === 'isUniversal'){
            getSysDomain()
        }
        var idNameTxt = "#"+idName+idx;
        for(var i = 1; i <= idLen; i ++){
            $("#"+idName+i).removeClass("sed");
        }
        $(idNameTxt).addClass("sed");
        if(idName === 'cloudVendor'){
            $("#accessKeySecret").val('');
            $("#accessKeyId").val('');
            //判断
            if(idNameTxt === '#cloudVendor1'){
                $("#cloudVendor").val('aly');
                //阿里云
                $("#cloudProductList").html('<label><input type="radio" checked value="aly-cdn" name="cloudProduct">&nbsp;&nbsp;CDN</label>\n' +
                    '                        <label style="margin-left: 10px;"><input type="radio" value="aly-dcdn" name="cloudProduct">&nbsp;&nbsp;DCDN</label>')
                $("#keyId").html('AccessKey ID：');
                $("#keySecret").html('AccessKey Secret：');
            }else if(idNameTxt === '#cloudVendor2'){
                $("#cloudVendor").val('qny');
                //七牛云
                $("#cloudProductList").html('<label><input type="radio" checked value="qny-cdn" name="cloudProduct">&nbsp;&nbsp;CDN</label>\n' +
                    '                        <label style="margin-left: 10px;"><input type="radio" value="qny-dcdn" name="cloudProduct">&nbsp;&nbsp;DCDN</label>')
                $("#keyId").html('AccessKey：');
                $("#keySecret").html('SecretKey：');
            }else{
                $("#cloudVendor").val('txy');
                //腾讯云
                $("#cloudProductList").html('<label><input type="radio" checked value="txy-cdn" name="cloudProduct">&nbsp;&nbsp;CDN</label>\n' +
                    '                        <label style="margin-left: 10px;"><input type="radio" value="txy-edgeOne" name="cloudProduct">&nbsp;&nbsp;EdgeOne</label>')
                $("#keyId").html('SecretId：');
                $("#keySecret").html('SecretKey：');
            }
            //重新绑定change事件
            $("input[type='radio'][name='cloudProduct']").change(function (e){
                getDomainList();
            })
        }
    }
    //重置表单的方法
    function formReset(){
        $("#certificateDomain").val('');
        $("#certificateDomain").attr("disabled", false);
        $("#tableBody").html('');
    }
    function submitHandler() {
        var data = $("#form-autoDeploy-add").serializeArray();
        if ($.validate.form()) {
            var isYz = $("#isYzOver").val();
            if(isYz && isYz === 'Y'){
                $.operate.saveTab(prefix + "/addCdn", data);
            }else{
                $.modal.msgError("请配置DNS解析记录！");
            }
        }
    }
</script>
</body>
<style type="text/css">
    .inputDiv{border: solid 2px #E4E4E7;align-content: center; text-align: center; padding: 5px 18px;position: relative; border-radius: 5px; margin-right: 5px;}
    .sed{border-color: #12B980; color: #12B980;}
</style>
